package org.example.controller;

import com.alibaba.fastjson.JSONArray;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.example.bean.Alipay;
import org.example.bean.Order;
import org.example.config.JwtConfig;
import org.example.service.OrderService;
import org.example.service.SeckillService;
import org.example.util.JsonResult;
import org.example.util.ResultTool;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@Controller
@RequestMapping("/seckill")
public class SeckillController {
    @Value("${appId}")
    private String appId;
    @Value("${privateKey}")
    private String privateKey;
    @Value("${publicKey}")
    private String publicKey;
    @Value("http://192.168.8.74:8001/seckill/success")
    private String notifyUrl;
    @Value("http://192.168.8.74:8001/seckill/success")
    private String returnUrl;
    @Value("${signType}")
    private String signType;
    @Value("${charset}")
    private String charset;
    @Value("${gatewayUrl}")
    private String gatewayUrl;

    @Resource
    private SeckillService seckillService;

    @GetMapping
    public String seckill(){
        JsonResult result = seckillService.seckill(this.token);
        System.out.println(result+"......");
        String bookId = result.getData().toString();
        this.total_amount=result.getError();
        System.out.println(this.total_amount+"././");
        ids[0]=bookId;
        return "redirect:/seckill/pay";
    }

    @GetMapping("/get_data")
    @ResponseBody
    public JsonResult getData(HttpServletRequest request) {
        this.token=request.getHeader("token");
        return ResultTool.success("success");
    }
    private String orderId;
    private String total_amount;
    private String token;
    private String[] ids={""};
    @Resource
    private OrderService orderService;

    @RequestMapping("/pay")
    @ResponseBody
    public String pay(Alipay alipayBean) throws AlipayApiException {
        alipayBean.setTotal_amount(this.total_amount);
        alipayBean.setSubject(this.ids[0].toString()+"的订单");
        alipayBean.setBody("秒杀的订单");
        // 生成一个订单号
        this.orderId = new Date().getTime() + "" + (int) (Math.random() * 10000);
        alipayBean.setOut_trade_no(this.orderId);
        // 产生Alipay客户端
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, appId, privateKey, "json", charset, publicKey, signType);
        // 调用支付宝接口
        AlipayTradePagePayRequest alipayTradeAppPayRequest = new AlipayTradePagePayRequest();
        System.out.println("进入了这里：" + alipayBean);
        // 设置付款成功后应跳转的路径
        alipayTradeAppPayRequest.setNotifyUrl(notifyUrl);
        alipayTradeAppPayRequest.setReturnUrl(returnUrl);
        // 设置支付宝的各项参数
        String json = JSONArray.toJSONString(alipayBean);
        alipayTradeAppPayRequest.setBizContent(json);
        System.out.println("支付的参数是：" + json);
        System.out.println(JSONArray.toJSONString(alipayTradeAppPayRequest));
        // 生成最终的订单
        return alipayClient.pageExecute(alipayTradeAppPayRequest).getBody();
    }

    @GetMapping("/success")
    public String success() {
        // 1. 生成订单向数据库中录入
        Order order = new Order();
        // user_id total_count total_amount id
        String userId = JwtConfig.parseJWT(token).get("id").toString();
        order.setId(orderId);
        order.setUserId(userId);
        order.setTotalAmount(total_amount);
        order.setTotalCount("1");
        orderService.saveOrder(order, ids);
        return "redirect:http://192.168.8.74:8080/front/index.html";
    }
}
